package com.sskj.jkzx.service.impl.yc;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sskj.jkzx.domain.entity.amap.yc.Pm10Qx;
import com.sskj.jkzx.domain.entity.amap.yc.param.MonitorDataByECodeParam;
import com.sskj.jkzx.domain.entity.amap.yc.ro.EDataPages;
import com.sskj.jkzx.domain.entity.amap.yc.ro.EquipmentInfo;
import com.sskj.jkzx.domain.entity.amap.yc.ro.EquipmentInfoMore;
import com.sskj.jkzx.domain.entity.amap.yc.ro.EquipmentInfoQx;
import com.sskj.jkzx.domain.entity.basic.BasicKV;
import com.sskj.jkzx.domain.entity.quantity.YCAlertQuantity;
import com.sskj.jkzx.domain.entity.yc.Camera;
import com.sskj.jkzx.domain.entity.yc.Weather;
import com.sskj.jkzx.repository.amap.message.MessageQueryServiceImpl;
import com.sskj.jkzx.service.impl.EngMarkersInfoServiceImpl;
import com.sskj.utils.HttpHelp;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "**/sskj/yc")
@Api(value = "扬尘数据查询", description = "扬尘数据查询")
public class YCDataServiceImpl {

	protected final Log logger = LogFactory.getLog(EngMarkersInfoServiceImpl.class);

	@Value("${sskj.ycServer}")
	private String ycServer;

	@Value("${sskj.jdServer}")
	private String jdServer;

	@Value("${sskj.amap.city}")
	private String defaultCity;

	@Autowired
	private YCCURDServiceImpl service;

	@Autowired
	MessageQueryServiceImpl messageQueryService;

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/edata/pcode", method = RequestMethod.GET)
	@ApiOperation(value = "工地扬尘实时数据查询", httpMethod = "GET")
	public List<EquipmentInfo> queryYCEquipmentInfo(String pcode) {
		List<EquipmentInfo> result = new ArrayList<EquipmentInfo>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("pcode", pcode);
		JSONObject resultJson;
		try {
			String resultStr = HttpHelp.sendGet(ycServer + "/getEquipmentinfoList.do", params);
			resultJson = JSONObject.parseObject(resultStr);
		} catch (Exception e) {
			logger.info(e.getMessage());
			resultJson = null;
		}
		if (resultJson != null) {
			result = JSON.parseArray(resultJson.getJSONArray("equipmentinfo").toJSONString(), EquipmentInfo.class);
		}
		return result;
	}

	/**
	 * 扬尘预警次数统计查询
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/tj/aq", method = RequestMethod.GET)
	@ApiOperation(value = "工地扬尘预警次数查询", httpMethod = "GET")
	public Map<String, Object> queryYCAlertQuantity() {
		YCAlertQuantity rs = service.getAlertQuantity();
		if (rs == null) {
			rs = new YCAlertQuantity();
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("yellowAlert", rs.getYellowAlert());
		result.put("redAlert", rs.getRedAlert());
		result.put("pCount", rs.getProjectsSum());
		result.put("qCountTotal", rs.getEquipSum());
		result.put("qCountNewly", rs.getNewlyEquips());
		result.put("tjrq", rs.getAlertdate());
		return result;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/edatas", method = RequestMethod.GET)
	@ApiOperation(value = "工地设备PM曲线图数据查询", httpMethod = "GET")
	public List<Pm10Qx> queryMonitorDataByECode(MonitorDataByECodeParam param) {
		List<Pm10Qx> result = new ArrayList<Pm10Qx>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("pcode", param.getPcode());
		params.put("limit", param.getSize());
		JSONObject resultJson;
		try {
			String resultStr = HttpHelp.sendGet(ycServer + "/queryMonitorDataByECode.do", params);
			resultJson = JSONObject.parseObject(resultStr);
		} catch (Exception e) {
			logger.info(e.getMessage());
			resultJson = null;
		}
		if (resultJson != null) {
			for (String key : resultJson.keySet()) {
				Pm10Qx r = new Pm10Qx();
				r.setName(key);
				List<EquipmentInfoQx> qxs = JSON.parseArray(resultJson.getJSONArray(key).toJSONString(),
						EquipmentInfoQx.class);
				List<String> pm10s = new ArrayList<String>();
				for (EquipmentInfoQx qx : qxs) {
					pm10s.add(qx.getPmTen());
				}
				r.setData(pm10s);
				result.add(r);
			}
		}
		return result;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/pm10top10", method = RequestMethod.GET)
	@ApiOperation(value = "PM10Top10数据查询", httpMethod = "GET")
	public List<String> queryPm10Rank() {
		List<EquipmentInfoMore> rs = new ArrayList<EquipmentInfoMore>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("limit", 10);
		JSONObject resultJson;
		try {
			String resultStr = HttpHelp.sendGet(ycServer + "/equipmentPmtenTopTen.do", params);
			resultJson = JSONObject.parseObject(resultStr);
		} catch (Exception e) {
			logger.info(e.getMessage());
			resultJson = null;
		}
		List<String> pm10s = new ArrayList<String>();
		if (resultJson != null) {
			rs = JSON.parseArray(resultJson.getJSONArray("topTen").toJSONString(), EquipmentInfoMore.class);
			for (EquipmentInfoMore d : rs) {
				pm10s.add(d.getPmTen());
			}
		}

		return pm10s;
	}

	/**
	 * 扬尘页面顶部统计数据（工程数量、设备数量、红色预警次数、黄色预警次数）
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/getAlertCount", method = RequestMethod.GET)
	@ApiOperation(value = "扬尘页面顶部统计数据（工程数量、设备数量、红色预警次数、黄色预警次数）", httpMethod = "GET")
	public Map<String, Object> getAlertCount() {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String responseStr = HttpHelp.sendGet(ycServer + "/getAlertCount.do", null);
			JSONObject responseJson = JSONObject.parseObject(responseStr);
			if (responseJson != null) {
				result.put("projectsSum", responseJson.getInteger("projectsSum"));
				result.put("equipSum", responseJson.getInteger("equipSum"));
				result.put("redAlert", responseJson.getInteger("redAlert"));
				result.put("yellowAlert", responseJson.getInteger("yellowAlert"));
			} else {
				result = null;
			}
			return result;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取已安装扬尘监控的工程数量
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/engCount", method = RequestMethod.GET)
	@ApiOperation(value = "获取已安装扬尘监控的工程数量", httpMethod = "GET")
	public BasicKV queryEngCount() {
		BasicKV result = new BasicKV("engCount", Integer.toString(service.getEngCount()));
		return result;
	}

	/**
	 * 获取扬尘监控设备总数
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/equipmentCount", method = RequestMethod.GET)
	@ApiOperation(value = "获取扬尘监控设备总数", httpMethod = "GET")
	public BasicKV queryEquipmentCount() {
		BasicKV result = new BasicKV("equipmentCount", Integer.toString(service.getEquipmentCount()));
		return result;
	}

	/**
	 * 获取扬尘监控黄色预警次数（当天）
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/yellowAlertCount", method = RequestMethod.GET)
	@ApiOperation(value = "获取扬尘监控黄色预警次数（当天）", httpMethod = "GET")
	public BasicKV queryYellowAlertCount() {
		long count = messageQueryService.findTodayCountByType("YA", 0);
		BasicKV result = new BasicKV("yellowAlertCount", Long.toString(count));
		return result;
	}

	/**
	 * 获取扬尘监控黄色预警次数（当天）
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/redAlertCount", method = RequestMethod.GET)
	@ApiOperation(value = "获取扬尘监控红色预警次数（当天）", httpMethod = "GET")
	public BasicKV queryRedAlertCount() {
		long count = messageQueryService.findTodayCountByType("RA", 0);
		BasicKV result = new BasicKV("redAlertCount", Long.toString(count));
		return result;
	}

	/**
	 * 获取过去10天预警次数
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/alertHistoryLastDay", method = RequestMethod.GET)
	@ApiOperation(value = "获取过去N天预警次数", httpMethod = "GET")
	public Map<String, List<Object>> queryAlertHistoryLastDay(Integer day) {
		if (day == null || day < 1) {
			day = 1;
		}
		Map<String, List<Object>> result = new HashMap<>();
		List<Object> yellow = new ArrayList<>();
		List<Object> red = new ArrayList<>();
		List<Object> days = new ArrayList<>();

		Calendar calendar = Calendar.getInstance();
		for (int i = day; i > 0; i--) {
			calendar.add(Calendar.DATE, i == day ? 1 - day : 1);
			String strDay = new SimpleDateFormat("MM-dd").format(calendar.getTime());
			days.add(strDay);
			yellow.add(messageQueryService.findTodayCountByType("YA", i - 1));
			red.add(messageQueryService.findTodayCountByType("RA", i - 1));
		}
		result.put("yellow", yellow);
		result.put("red", red);
		result.put("days", days);
		return result;
	}

	/**
	 * 获取过去10天预警次数
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/alertHistoryLastDay2", method = RequestMethod.GET)
	@ApiOperation(value = "获取过去N天预警次数", httpMethod = "GET")
	public Map<String, List<Object>> queryAlertHistoryLastDay2(Integer day) {
		if (day == null || day < 1) {
			day = 1;
		}
		Map<String, List<Object>> result = new HashMap<>();
		List<Object> yellow = new ArrayList<>();
		List<Object> red = new ArrayList<>();
		List<Object> days = new ArrayList<>();

		try {
			Calendar now = Calendar.getInstance();
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Map<String, Object> params = new HashMap<String, Object>();
			now.add(Calendar.DAY_OF_YEAR, -1);
			params.put("endtime", df.format(now.getTime()));
			now.add(Calendar.DAY_OF_YEAR, 1 - day);
			params.put("starttime", df.format(now.getTime()));
			String resultStr = HttpHelp.sendGet(ycServer + "/betweenTimeWorkInfo.do", params);
			JSONArray resultJson = JSONObject.parseArray(resultStr);
			resultJson.forEach(json -> {
				JSONObject jsonObject = JSONObject.parseObject(json.toString());
				if (jsonObject != null) {
					days.add(jsonObject.getString("alertdate"));
					yellow.add(jsonObject.getString("yellow"));
					red.add(jsonObject.getString("red"));
				}
			});
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		result.put("yellow", yellow);
		result.put("red", red);
		result.put("days", days);
		return result;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/alertCountRank", method = RequestMethod.GET)
	@ApiOperation(value = "当日工程预警次数排名", httpMethod = "GET")
	public JSONArray queryAlertCountRank() {
		try {
			String response = HttpHelp.sendGet(ycServer + "/yesterdayWorkInfo.do", null);
			return JSONObject.parseArray(response);
		} catch (Exception e) {
			e.printStackTrace();
			return new JSONArray();
		}
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/todayWorkInfoByEcode", method = RequestMethod.GET)
	@ApiOperation(value = "当日扬尘数据", httpMethod = "GET")
	public JSONArray todayWorkInfoByEcode(@RequestParam Map<String, Object> params) {
		try {
			String response = HttpHelp.sendGet(ycServer + "/todayWorkInfoByEcode.do", params);
			return JSONObject.parseArray(response);
		} catch (Exception e) {
			e.printStackTrace();
			return new JSONArray();
		}
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "**/queryWeatherInfo", method = { RequestMethod.GET })
	@ApiOperation(value = "加载绿色工地main天气状况数据", httpMethod = "GET")
	public Weather queryWeatherInfo(String city) {
		Map<String, Object> querys = new HashMap<>();
		querys.put("city", city == null ? defaultCity : city);
		String path = "/weiQueryWeatherInfo.do";
		Weather result = new Weather(0, 0, "无");
		try {
			String response = HttpHelp.sendGet(ycServer + path, querys);
			JSONObject jsonResponse = JSONObject.parseObject(response);
			if (jsonResponse != null) {
				String pm25 = jsonResponse.getString("pm25");
				try {
					result.setPm25(Double.parseDouble(pm25));
				} catch (Exception e) {
					result.setPm25(0);
				}
				result.setQuality(jsonResponse.getString("quality"));
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "**/queryCamera", method = { RequestMethod.GET })
	@ApiOperation(value = "获取摄像头", httpMethod = "GET")
	public List<Camera> queryCamera(String engId) {
		List<Camera> result = new ArrayList<>();
		if (engId == null) {
			return result;
		}
		String url = jdServer + "/seam/resource/v1/appvideo/fromyc/" + engId;
		try {
			String response = HttpHelp.sendGet(url, null);
			result = JSONObject.parseArray(response, Camera.class);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "**/edata/page", method = { RequestMethod.GET })
	public Map<String, Object> queryEDatas(Integer page, Integer size, String ename) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<EDataPages> responseEntity = new ArrayList<>();
		int totalCount = 0;
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("rows", size);
			params.put("page", page);
			params.put("ename", ename);
			params.put("gcjd", "在建");
			String responseStr = HttpHelp.sendGet(ycServer + "/equipmentPageList.do", params);
			JSONObject responseJson = JSONObject.parseObject(responseStr);
			if (responseJson != null) {
				responseEntity = JSONObject.parseArray(responseJson.getString("rows"), EDataPages.class);
				totalCount = responseJson.getIntValue("total");
			}
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		result.put("data", responseEntity);
		result.put("currentPage", page);
		result.put("totalCount", totalCount);
		return result;
	}

}
